Node.js Interface Reference

Node.js readline தொகுதியில் Interface பொருள் மற்றும் கட்டளை வரி இடைமுகங்களை உருவாக்க கற்றுக்கொள்ளுங்கள்

Interface பொருள்

Interface வகுப்பு Node.js இல் உள்ள readline தொகுதியின் ஒரு பகுதியாகும். இது Readable ஸ்ட்ரீமில் இருந்து (process.stdin போன்ற) தரவை ஒரு நேரத்தில் ஒரு வரியாக வாசிக்க ஒரு வழியை வழங்குகிறது. இது கட்டளை வரி இடைமுகங்கள் (CLIs) மற்றும் ஊடாடும் கேள்விகளை உருவாக்க பொதுவாகப் பயன்படுத்தப்படுகிறது.

கட்டளை வரி இடைமுகங்கள்

CLI பயன்பாடுகள் மற்றும் கட்டளை கருவிகளை உருவாக்க உதவுகிறது

ஊடாடும் கேள்விகள்

பயனர்களிடமிருந்து உள்ளீட்டைப் பெற ஊடாடும் வழிகளை வழங்குகிறது

ஸ்ட்ரீம் கையாளுதல்

Readable மற்றும் Writable ஸ்ட்ரீம்களுடன் நேரடியாக வேலை செய்கிறது

readline தொகுதியை இறக்குமதி செய்தல்

// Import the readline module
const readline = require('readline');

// Create an Interface instance
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

Interface பண்புகள்

பண்பு விளக்கம்
rl.line தற்போது செயலாக்கப்படும் உள்ளீட்டு வரி
rl.cursor தற்போதைய வரியில் கர்சர் நிலை
rl.input பயன்படுத்தப்படும் Readable ஸ்ட்ரீம்
rl.output பயன்படுத்தப்படும் Writable ஸ்ட்ரீம்
rl.terminal ஸ்ட்ரீம் TTY போலவே நடத்தப்பட வேண்டுமா மற்றும் ANSI/VT100 எஸ்கேப் குறியீடுகள் எழுதப்பட வேண்டுமா என்பதைக் குறிக்கும் பூலியன்
rl.history வரலாறு பஃபர் வழங்கப்பட்டிருந்தால். Promise-அடிப்படையிலான API பயன்படுத்தும் போது இது கிடைக்காது

Interface முறைகள்

முறை விளக்கம்
rl.question(query, callback) கேள்வியைப் பயனருக்குக் காட்டி அவர்களின் உள்ளீட்டிற்காகக் காத்திருக்கிறது. அவர்கள் வழங்கியவுடன், பயனரின் உள்ளீட்டை அதன் முதல் வாதமாகக் கொண்டு callback ஐ அழைக்கிறது
rl.close() Interface நிகழ்வை மூடுகிறது, உள்ளீடு மற்றும் வெளியீட்டு ஸ்ட்ரீம்களின் கட்டுப்பாட்டை விட்டுக்கொடுக்கிறது
rl.pause() readline உள்ளீட்டு ஸ்ட்ரீமை இடைநிறுத்துகிறது, அது பின்னர் மீண்டும் தொடங்க அனுமதிக்கிறது
rl.resume() readline உள்ளீட்டு ஸ்ட்ரீமை மீண்டும் தொடங்குகிறது
rl.write(data[, key]) வெளியீட்டு ஸ்ட்ரீமில் தரவை எழுதுகிறது. key வாதம் ctrl அல்லது meta போன்ற சிறப்பு எழுத்துகளைக் கொண்ட ஒரு பொருளாக இருக்கலாம்
rl.prompt([preserveCursor]) பயனர் உள்ளீடு செய்வதற்கான prompt ஐக் காட்டுகிறது. preserveCursor true எனில், கர்சர் நிலை மீட்டமைக்கப்படாது
rl.getPrompt() தற்போதைய prompt சரத்தை வழங்குகிறது
rl.setPrompt(prompt) rl.prompt() அழைக்கப்படும் போது காட்டப்படும் prompt சரத்தை அமைக்கிறது

Interface நிகழ்வுகள்

நிகழ்வு விளக்கம்
'close' Interface நிகழ்வு மூடப்படும் போது உமிழப்படுகிறது
'line' பயனர் Enter விசையை அழுத்தி உள்ளீட்டின் ஒரு வரியைச் சமர்ப்பிக்கும் போது உமிழப்படுகிறது
'pause' உள்ளீட்டு ஸ்ட்ரீம் இடைநிறுத்தப்படும் போது உமிழப்படுகிறது
'resume' உள்ளீட்டு ஸ்ட்ரீம் மீண்டும் தொடங்கப்படும் போது உமிழப்படுகிறது
'SIGCONT' முன்பு Ctrl+Z (SIGTSTP) உடன் இடைநிறுத்தப்பட்ட Node.js செயல்முறை மீண்டும் தொடங்கப்படும் போது உமிழப்படுகிறது
'SIGINT' Ctrl+C அழுத்தப்படும் போது உமிழப்படுகிறது, SIGINT என அறியப்படுகிறது
'SIGTSTP' Ctrl+Z அழுத்தப்படும் போது உமிழப்படுகிறது, SIGTSTP என அறியப்படுகிறது
'history' வரலாறு மாறும் போதெல்லாம் உமிழப்படுகிறது

அடிப்படை பயன்பாடு எடுத்துக்காட்டு

இந்த எடுத்துக்காட்டு ஒரு எளிய கட்டளை வரி prompt உருவாக்க Interface பொருளின் அடிப்படை பயன்பாட்டை நிரூபிக்கிறது:

const readline = require('readline');

// Create interface for reading from stdin and writing to stdout
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// Ask a question and get the user's input
rl.question('What is your name? ', (name) => {
  console.log(`Hello, ${name}!`);

  // Ask another question
  rl.question('How are you today? ', (response) => {
    console.log(`Glad to hear: ${response}`);
    
    // Close the interface
    rl.close();
  });
});

// Handle the close event
rl.on('close', () => {
  console.log('Interface closed. Goodbye!');
});

Promise-அடிப்படையிலான API எடுத்துக்காட்டு

Node.js v17+ readline க்கு promise-அடிப்படையிலான API ஐ வழங்குகிறது:

// For Node.js v17 and above:
const readline = require('readline/promises');
const { stdin: input, stdout: output } = require('process');

async function askQuestions() {
  const rl = readline.createInterface({ input, output });

  try {
    // Ask questions sequentially
    const name = await rl.question('What is your name? ');
    console.log(`Hello, ${name}!`);

    const age = await rl.question('How old are you? ');
    console.log(`You are ${age} years old.`);

    const location = await rl.question('Where do you live? ');
    console.log(`${location} is a nice place!`);

    // Summary
    console.log('\nSummary:');
    console.log(`Name: ${name}`);
    console.log(`Age: ${age}`);
    console.log(`Location: ${location}`);
  } finally {
    // Make sure to close the interface
    rl.close();
  }
}

// Run the async function
askQuestions()
  .then(() => console.log('Questions completed!'))
  .catch(err => console.error('Error:', err));

கட்டளை வரி இடைமுக எடுத்துக்காட்டு

வரலாறு ஆதரவுடன் ஒரு எளிய கட்டளை வரி இடைமுகத்தை உருவாக்குதல்:

const readline = require('readline');
const fs = require('fs');
const path = require('path');

// History file path
const historyFile = path.join(__dirname, '.command_history');

// Load command history if it exists
let commandHistory = [];
try {
  if (fs.existsSync(historyFile)) {
    commandHistory = fs.readFileSync(historyFile, 'utf8')
      .split('\n')
      .filter(cmd => cmd.trim());
  }
} catch (err) {
  console.error('Error loading history:', err.message);
}

// Create the interface with custom configuration
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'cli> ',
  historySize: 100,
  history: commandHistory
});

// Available commands
const commands = {
  help: () => {
    console.log('\nAvailable commands:');
    console.log('  help     - Show this help message');
    console.log('  hello    - Say hello');
    console.log('  date     - Show current date and time');
    console.log('  clear    - Clear the console');
    console.log('  exit     - Exit the CLI');
    rl.prompt();
  },
  hello: () => {
    console.log('Hello, world!');
    rl.prompt();
  },
  date: () => {
    console.log(new Date().toLocaleString());
    rl.prompt();
  },
  clear: () => {
    process.stdout.write('\x1Bc');
    rl.prompt();
  },
  exit: () => {
    // Save command history to file
    try {
      fs.writeFileSync(historyFile, rl.history.join('\n'));
      console.log(`Command history saved to ${historyFile}`);
    } catch (err) {
      console.error('Error saving history:', err.message);
    }
    
    console.log('Goodbye!');
    rl.close();
  }
};

// Display welcome message
console.log('Simple CLI Example');
console.log('Type "help" for available commands');

// Display the prompt
rl.prompt();

// Handle input
rl.on('line', (line) => {
  const input = line.trim();
  
  if (input === '') {
    rl.prompt();
    return;
  }
  
  const command = input.toLowerCase();
  
  if (commands[command]) {
    commands[command]();
  } else {
    console.log(`Command not found: ${input}`);
    console.log('Type "help" for available commands');
    rl.prompt();
  }
}).on('close', () => {
  process.exit(0);
});

// Handle Ctrl+C (SIGINT)
rl.on('SIGINT', () => {
  rl.question('Are you sure you want to exit? (y/n) ', (answer) => {
    if (answer.toLowerCase() === 'y') {
      commands.exit();
    } else {
      console.log('Operation cancelled');
      rl.prompt();
    }
  });
});

ஊடாடும் கடவுச்சொல் உள்ளீடு

உள்ளிடப்பட்ட எழுத்துகளை மறைக்கும் கடவுச்சொல் உள்ளீட்டை உருவாக்குதல்:

const readline = require('readline');

// Create the interface
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// Function to prompt for masked input
function promptPassword(query) {
  return new Promise((resolve) => {
    // Create a hidden readline instance to control input/output
    const stdin = process.stdin;
    
    // Save the original configuration
    const originalStdinIsTTY = stdin.isTTY;
    if (originalStdinIsTTY) {
      stdin.setRawMode(true);
    }
    
    let password = '';
    
    // Write the query
    process.stdout.write(query);
    
    // Handle keypress events
    const onData = (key) => {
      // Ctrl+C
      if (key.toString() === '\u0003') {
        process.stdout.write('\n');
        process.exit();
      }
      
      // Enter key
      if (key.toString() === '\r' || key.toString() === '\n') {
        if (originalStdinIsTTY) {
          stdin.setRawMode(false);
        }
        stdin.removeListener('data', onData);
        process.stdout.write('\n');
        resolve(password);
        return;
      }
      
      // Backspace
      if (key.toString() === '\u0008' || key.toString() === '\u007f') {
        if (password.length > 0) {
          password = password.slice(0, -1);
          process.stdout.write('\b \b'); // Erase last character
        }
        return;
      }
      
      // Regular character
      password += key.toString();
      process.stdout.write('*'); // Show asterisk for each character
    };
    
    stdin.on('data', onData);
  });
}

// Example usage
async function login() {
  const username = await new Promise((resolve) => {
    rl.question('Username: ', (answer) => {
      resolve(answer);
    });
  });
  
  const password = await promptPassword('Password: ');
  
  console.log(`\nAttempting login for user: ${username}`);
  
  // Simulate authentication check
  if (username === 'admin' && password === 'password') {
    console.log('Login successful!');
  } else {
    console.log('Invalid username or password');
  }
  
  rl.close();
}

// Start the login process
login();

ஊடாடும் மெனு எடுத்துக்காட்டு

விருப்பங்களுடன் ஒரு ஊடாடும் மெனுவை உருவாக்குதல்:

const readline = require('readline');

// Create the interface
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// Menu options
const menuOptions = [
  { id: 1, name: 'View Profile' },
  { id: 2, name: 'Edit Settings' },
  { id: 3, name: 'Check Messages' },
  { id: 4, name: 'Log Out' },
  { id: 5, name: 'Exit' }
];

// Display the menu
function displayMenu() {
  console.log('\n===== MAIN MENU =====');
  menuOptions.forEach(option => {
    console.log(`${option.id}. ${option.name}`);
  });
  console.log('====================');
}

// Process the selected option
function processOption(option) {
  const selectedOption = menuOptions.find(item => item.id === parseInt(option));
  
  if (!selectedOption) {
    console.log('Invalid option. Please try again.');
    return promptUser();
  }
  
  console.log(`\nYou selected: ${selectedOption.name}`);
  
  // Handle each option
  switch (selectedOption.id) {
    case 1:
      console.log('Displaying user profile...');
      console.log('Name: John Doe');
      console.log('Email: john@example.com');
      console.log('Role: Administrator');
      break;
    case 2:
      console.log('Opening settings menu...');
      console.log('(Settings options would be displayed here)');
      break;
    case 3:
      console.log('Checking messages...');
      console.log('You have no new messages.');
      break;
    case 4:
      console.log('Logging out...');
      console.log('You have been logged out successfully.');
      return rl.close();
    case 5:
      console.log('Exiting the application...');
      return rl.close();
  }
  
  // Return to the menu after a short delay
  setTimeout(() => {
    promptUser();
  }, 1500);
}

// Prompt the user to select an option
function promptUser() {
  displayMenu();
  rl.question('Select an option: ', (answer) => {
    processOption(answer);
  });
}

// Start the menu
console.log('Welcome to the Interactive Menu Example');
promptUser();

// Handle close event
rl.on('close', () => {
  console.log('\nThank you for using the application!');
  process.exit(0);
});

சிறந்த நடைமுறைகள்

Interface ஐ எப்போதும் மூடவும்: நீங்கள் முடித்தவுடன் rl.close() ஐ அழைக்கவும், வளங்களை விடுவிக்க
Ctrl+C ஐ கையாளவும்: நிரல் முடிவை நேர்த்தியாக கையாள 'SIGINT' நிகழ்வைக் கேளுங்கள்
Promise-அடிப்படையிலான API ஐப் பயன்படுத்தவும்: Node.js v17 மற்றும் அதற்கு மேல், சுத்தமான async குறியீட்டிற்கு promise-அடிப்படையிலான API ஐக் கருத்தில் கொள்ளுங்கள்
வரலாற்றைச் சேமிக்கவும்: CLI பயன்பாடுகளுக்கு, சிறந்த பயனர் அனுபவத்தை வழங்க கட்டளை வரலாற்றைச் சேமித்து மீட்டமைக்கவும்
பிழைகளைக் கையாளவும்: பயனருடன் தொடர்பு கொள்ளும் போது சாத்தியமான பிழைகளை எப்போதும் கையாளவும்
தெளிவான prompts வழங்கவும்: எந்த வகையான உள்ளீடு எதிர்பார்க்கப்படுகிறது என்பதை உங்கள் prompts தெளிவாகக் குறிக்கிறதா என்பதை உறுதிப்படுத்திக் கொள்ளுங்கள்
உள்ளீட்டைச் சரிபார்க்கவும்: அதைச் செயலாக்குவதற்கு முன் பயனர் உள்ளீட்டை எப்போதும் சரிபார்க்கவும்

பயிற்சி

Node.js இல் readline Interface உருவாக்க பயன்படுத்தப்படும் சரியான முறையைத் தேர்ந்தெடுக்கவும்.

readline.startInterface()
✗ தவறு! "readline.startInterface()" என்பது Node.js இல் ஒரு செல்லுபடியாகும் முறை அல்ல
readline.newInterface()
✗ தவறு! "readline.newInterface()" என்பது Node.js இல் ஒரு செல்லுபடியாகும் முறை அல்ல
readline.createInterface()
✓ சரி! "readline.createInterface()" என்பது Node.js இல் readline Interface உருவாக்க பயன்படும் சரியான முறையாகும்
readline.initInterface()
✗ தவறு! "readline.initInterface()" என்பது Node.js இல் ஒரு செல்லுபடியாகும் முறை அல்ல